/**
 * 新增修改完成调用 modalFormOk方法 编辑弹框组件ref定义为modalForm
 * 高级查询按钮调用 superQuery方法  高级查询组件ref定义为superQueryModal
 * data中url定义 list为查询列表  delete为删除单条记录  deleteBatch为批量删除
 */
import { filterObj } from '@/utils/util'
import { deleteAction, downFile, getAction, getFileAccessHttpUrl } from '@/api/manage'
import Vue from 'vue'
import { ACCESS_TOKEN, TENANT_ID } from '@/store/mutation-types'
import store from '@/store'
import { mapGetters } from 'vuex';
import { Modal } from 'ant-design-vue'

import AuditModal from '@/views/scy/components/AuditModal'
export const JeecgListMixin = {
  components: {
    AuditModal,
  },
  data() {
    return {
      exportLoading: false,
      /* 查询条件-请不要在queryParam中声明非字符串值的属性 */
      queryParam: {},
      /* 数据源 */
      dataSource: [],
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30', '50', '100', '200'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      /* 排序参数 */
      isorter: {
        column: 'createTime',
        order: 'desc'
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 19 },
      },
      /* 筛选参数 */
      filters: {},
      /* table加载状态 */
      loading: false,
      /* table选中keys */
      selectedRowKeys: [],
      /* table选中records */
      selectionRows: [],
      /* 查询折叠 */
      toggleSearchStatus: false,
      /* 高级查询条件生效状态 */
      superQueryFlag: false,
      /* 高级查询条件 */
      superQueryParams: '',
      /** 高级查询拼接方式 */
      superQueryMatchType: 'and',
      iconStyle: { 'font-size': '18px', 'cursor': 'pointer' },
      colsettings: ':colsettings',
      domTable:null,
      //新增的最重要的查询参数，这个放在最后，能够覆盖前面的同名参数，这里的设置只是为了不报错，在自己页面自定义 
      mostImportantParams: {
        
      },
      // 导出用的参数
      exportParams:{},
      controlLoadData:false,
      controlColumns:false
    }
  },
  // mounted() {
  //   this.domTable = document.querySelector(".ant-table-body")
  //   this.domTable.addEventListener("mousedown", this.resize);
  //   this.domTable.addEventListener("mouseover", this.resize);
  //   this.domTable.addEventListener("mouseup", this.resize);
  // },
  // beforeDestroy() {
  //   this.domTable.removeEventListener("mousedown", this.resize);
  //   this.domTable.removeEventListener("mouseover", this.resize);
  //   this.domTable.removeEventListener("mouseup", this.resize);
  // },
  created() {
    if (!this.disableMixinCreated) {
      console.log(' -- mixin created -- ')
      !this.controlLoadData&&this.loadData()
      // 初始化字典配置 在自己页面定义
      this.initDictConfig()
      !this.controlColumns&&this.initColumns()
    }
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        '0': '待提交',
        '1': '待审核',
        '2': '已审核'
      }
      return statusMap[status] || status
    },
    statusTypeFilter(type) {
      const statusTypeMap = {
        '0': 'success',
        '1': 'success',
        '2': 'success'
      }
      return statusTypeMap[type] || 'success'
    }
  },
  computed: {
    // token header
    tokenHeader() {
      let head = {
        'Authorization': Vue.ls.get(ACCESS_TOKEN),
        'client-id': 'web',
        'user-id': Vue.ls.get('user_id') || ''
      }
      let tenantid = Vue.ls.get(TENANT_ID)
      if (tenantid) {
        head['tenant_id'] = tenantid
      }
      return head
    },
    draggableComponent: function() {
      return this.dragResizable(this.columns)
    },
    // 动态获取scrollX,防止数组固定列的大小变化
    scrollX() {
      return this.columns.reduce((preVal, curVal) => {
        return preVal + curVal.width
      }, 0)
    }
  },
  methods: {
    ...mapGetters(['userInfo']), // 用户信息
    // 点击获取单据来源
    handleDocumentSource () {
      if (this.queryParam.permissionType == 3) {
        // 本部门
        if (this.queryParam && this.queryParam.teamIds) {
          this.queryParam.teamIds = ''
        }
        this.getDepartName = []
        this.getTeamName = []
        var params1 = {
          username: this.userInfo().username
        }
        getAction('/api/erpmng/sys/sysDepart/getDepartByUserName', params1).then((res) => {
          if (res.success) {
            this.getDepartName = res.result
          } else {
            this.$message.warning('未查询到部门信息')
          }
      })
      } else if (this.queryParam.permissionType == 4) {
        // 本团队
        if (this.queryParam && this.queryParam.deptIds) {
          this.queryParam.deptIds = ''
        }
        this.getDepartName = []
        this.getTeamName = []
        var params2 = {
          userId: this.userInfo().empId
        }
        getAction('/api/erp/omc/teammanager/erpOmcTeamManager/getTeamByUserId', params2).then((res) => {
          if (res.success) {
            console.log("获取团队信息", res);
            this.getTeamName = res.result
          } else {
            this.$message.warning('未查询到团队信息')
          }
        })
      } else {
        this.queryParam.teamIds = ''
        this.queryParam.deptIds = ''
        this.getDepartName = []
        this.getTeamName = []
      }
    },
    resize(){
      if(this.domTable.scrollWidth > this.domTable.clientWidth){
        this.columns.forEach(val => {
          if(val.dataIndex == 'action'){
            val.fixed = 'right'
          }
        })
      } else {
        this.columns.forEach(val => {
          if(val.dataIndex == 'action'){
            delete val.fixed
          }
        })
      }
    },
    async loadData(arg) {
      console.log("查询参数mixin",arg);
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      // 加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
        
      }
      var params = this.getQueryParams() // 查询条件
      params.pageUrl = this.$route.path
      // params.postDataSource = 'company'
      console.log("查询参数", params);
      
      this.loading = true
      return getAction(this.url.list, params).then(res => {
        if (res.success) {
          
          // update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          this.dataSource = res.result.records || res.result
          if (res.result.total) {
            this.ipagination.total = res.result.total
          } else {
            this.ipagination.total = 0
          }
          //判断是否当前页没有数据且不为第一页
          if (this.dataSource.length == 0 && this.ipagination.current != 1) {
            this.ipagination.current = this.ipagination.current - 1
            this.loadData(this.ipagination.current - 1);
          }
          // update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
        } else {
          this.dataSource = [];
          this.ipagination.total = 0
          this.$message.warning(res.message)
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        this.loading = false
      }).catch(err => {
        this.$message.warning(err.message)
      })
    },
    // 新增流程取消关闭弹窗刷新页面
    handleClose () {
      this.$refs.modalForm.handleCancel()
      this.loadData();
    },
    initDictConfig() {
      console.log('--这是一个假的方法!')
    },
    handleSuperQuery(params, matchType) {
      // 高级查询方法
      if (!params) {
        this.superQueryParams = ''
        this.superQueryFlag = false
      } else {
        this.superQueryFlag = true
        this.superQueryParams = JSON.stringify(params)
        this.superQueryMatchType = matchType
      }
      this.loadData(1)
    },
    getQueryParams() {
      // 获取查询条件
      let sqp = {}
      if (this.superQueryParams) {
        sqp['superQueryParams'] = encodeURI(this.superQueryParams)
        sqp['superQueryMatchType'] = this.superQueryMatchType
      }
      // 新增不会被覆盖的查询参数
      var param = Object.assign(sqp, this.queryParam, this.isorter, this.filters,this.exportParams,this.mostImportantParams)
      param.field = this.getQueryField()
      param.pageNo = this.ipagination.current
      param.pageSize = this.mostImportantParams.pageSize!=-1?this.ipagination.pageSize:this.mostImportantParams.pageSize
      return filterObj(param)
    },
    getQueryField() {
      // TODO 字段权限控制
      var str = 'id'
      this.columns.forEach(function (value) {
        // 多表头字段
        if (value.dataIndex == null && value.dataIndex === undefined) {
          value.children.forEach(function (item) {
            str += ',' + item.dataIndex.replace('_dictText', '')
          })
        } else {
          str += ',' + value.dataIndex
        }
      })
      return str
    },

    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },
    onClearSelected() {
      this.selectedRowKeys = []
      this.selectionRows = []
    },
    searchQuery() {
      this.onClearSelected();
      this.loadData(1)
    },
    superQuery() {
      this.$refs.superQueryModal.show()
    },
    searchReset() {
      this.onClearSelected();
      this.queryParam = {}
      this.loadData(1)
    },
    batchDel: function () {
      if (!this.url.deleteBatch) {
        this.$message.error('请设置url.deleteBatch属性!')
        return
      }
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！')
      } else {
        var ids = ''
        for (var a = 0; a < this.selectedRowKeys.length; a++) {
          ids += this.selectedRowKeys[a] + ','
        }
        var that = this
        this.$confirm({
          title: '确认删除',
          content: '是否删除选中数据?',
          onOk: function () {
            that.loading = true
            deleteAction(that.url.deleteBatch, {
              ids: ids
            })
              .then(res => {
                if (res.success) {
                  that.$message.success(res.message)
                  that.loadData()
                  that.onClearSelected()
                  //判断是否有search对象
                  if (that.$refs.search != undefined) {
                    //重置Dict数据
                    that.$refs.search.initDictData();
                  }
                  if (that.$refs.search2 != undefined) {
                    that.$refs.search2.initDictData();
                  }
                } else {
                  that.$message.warning(res.message)
                }
              })
              .finally(() => {
                that.loading = false
              })
          }
        })
      }
    },
    batchSubmit: function () {
      if (!this.url.submitBatch) {
        this.$message.error('请设置url.submitBatch属性!')
        return
      }
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！')
      } else {
        var ids = ''
        for (var a = 0; a < this.selectedRowKeys.length; a++) {
          ids += this.selectedRowKeys[a] + ','
        }
        var that = this
        this.$confirm({
          title: '确认提交',
          content: '是否提交选中数据?',
          onOk: function () {
            that.loading = true
            getAction(that.url.submitBatch, {
              ids: ids
            })
              .then(res => {
                if (res.success) {
                  that.$message.success(res.message)
                  that.loadData()
                  that.onClearSelected()
                } else {
                  that.$message.warning(res.message)
                }
              })
              .finally(() => {
                that.loading = false
              })
          }
        })
      }
    },
    batchRevoke: function () {
      if (!this.url.revokeBatch) {
        this.$message.error('请设置url.revokeBatch属性!')
        return
      }
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！')
      } else {
        var ids = ''
        for (var a = 0; a < this.selectedRowKeys.length; a++) {
          ids += this.selectedRowKeys[a] + ','
        }
        var that = this
        this.$confirm({
          title: '确认撤销',
          content: '是否撤销选中数据?',
          onOk: function () {
            that.loading = true
            getAction(that.url.revokeBatch, {
              ids: ids
            })
              .then(res => {
                if (res.success) {
                  that.$message.success(res.message)
                  that.loadData()
                  that.onClearSelected()
                  if (that.$refs.search != undefined) {
                    that.$refs.search.initDictData();
                  }
                  if (that.$refs.search2 != undefined) {
                    that.$refs.search2.initDictData();
                  }
                } else {
                  that.$message.warning(res.message)
                }
              })
              .finally(() => {
                that.loading = false
              })
          }
        })
      }
    },
    batchAudit: function () {
      if (!this.url.auditBatch) {
        this.$message.error('请设置url.auditBatch属性!')
        return
      }
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！')
      } else {
        var ids = ''
        for (var a = 0; a < this.selectedRowKeys.length; a++) {
          ids += this.selectedRowKeys[a] + ','
        }
        this.$refs.auditModal.url = this.url
        this.$refs.auditModal.showModal(ids, this.selectedRowKeys.length)
      }
    },
    batchCounterTrial: function () {
      if (!this.url.counterTrialBatch) {
        this.$message.error('请设置url.counterTrialBatch属性!')
        return
      }
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！')
      } else {
        var ids = ''
        for (var a = 0; a < this.selectedRowKeys.length; a++) {
          ids += this.selectedRowKeys[a] + ','
        }
        var that = this
        this.$confirm({
          title: '确认反审',
          content: '是否反审选中数据?',
          onOk: function () {
            that.loading = true
            getAction(that.url.counterTrialBatch, {
              ids: ids
            })
              .then(res => {
                if (res.success) {
                  that.$message.success(res.message)
                  that.loadData()
                  that.onClearSelected()
                  if (that.$refs.search != undefined) {
                    that.$refs.search.initDictData();
                  }
                  if (that.$refs.search2 != undefined) {
                    that.$refs.search2.initDictData();
                  }
                } else {
                  that.$message.warning(res.message)
                }
              })
              .finally(() => {
                that.loading = false
              })
          }
        })
      }
    },
    handleDelete: function (id) {
      if (!this.url.delete) {
        this.$message.error('请设置url.delete属性!')
        return
      }
      var that = this
      deleteAction(that.url.delete, {
        id: id
      }).then(res => {
        if (res.success) {
          that.$message.success(res.message)
          that.loadData()
          if (that.$refs.search != undefined) {
            that.$refs.search.initDictData();
          }
          if (that.$refs.search2 != undefined) {
            that.$refs.search2.initDictData();
          }
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    handleSubmit: function (id) {
      if (!this.url.submit) {
        this.$message.error('请设置url.submit属性!')
        return
      }
      var that = this
      getAction(that.url.submit, {
        id: id
      }).then(res => {
        if (res.success) {
          that.$message.success(res.message)
          that.loadData()
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    handleAudit: function (id) {
      if (!this.url.audit) {
        this.$message.error('请设置url.audit属性!')
        return
      }
      this.$refs.auditModal.url = this.url
      this.$refs.auditModal.showModal(id, 1)

    },
    handleRevoke: function (id) {
      if (!this.url.revoke) {
        this.$message.error('请设置url.revoke属性!')
        return
      }
      var that = this
      getAction(that.url.revoke, {
        id: id
      }).then(res => {
        if (res.success) {
          that.$message.success(res.message)
          that.loadData()

          if (that.$refs.search != undefined) {
            that.$refs.search.initDictData();
          }
          if (that.$refs.search2 != undefined) {
            that.$refs.search2.initDictData();
          }
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    handleCounterTrial: function (id) {
      if (!this.url.counterTrial) {
        this.$message.error('请设置url.counterTrial属性!')
        return
      }
      var that = this
      getAction(that.url.counterTrial, {
        id: id
      }).then(res => {
        if (res.success) {
          that.$message.success(res.message)
          that.loadData()
          if (that.$refs.search != undefined) {
            that.$refs.search.initDictData();
          }
          if (this.$refs.search2 != undefined) {
            this.$refs.search2.initDictData();
          }
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    handleEdit: function (record) {
      //debugger;
      this.$refs.modalForm.edit(record)
      this.$refs.modalForm.title = '编辑'
      this.$refs.modalForm.disableSubmit = false
    },
    handleAdd: function () {
      this.$refs.modalForm.add()
      this.$refs.modalForm.title = '新增'
      this.$refs.modalForm.disableSubmit = false
    },
    handleAddTab: function () {
    },
    handleTableChange(pagination, filters, sorter) {
      // 分页、排序、筛选变化时触发
      this.filters = {}
      if (Object.keys(filters).length > 0) {
        for (let key in filters) {
          let value = filters[key].join(',')
          if (value) {
            if (key.indexOf('_dictText') != -1) {
              key = key.substring(0, key.indexOf('_dictText'))
            }
            this.filters[key] = value
          }
        }
      }
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = sorter.order == 'ascend' ? 'asc' : 'desc'
      }
      this.ipagination = pagination
      this.loadData()
    },
    handleToggleSearch() {
      this.toggleSearchStatus = !this.toggleSearchStatus
    },
    // 给popup查询使用(查询区域不支持回填多个字段，限制只返回一个字段)
    getPopupField(fields) {
      return fields.split(',')[0]
    },
    // modalFormOk() {
    //   // 新增/修改 成功时，重载列表
    //   this.loadData()
    //   // 清空列表选中
    //   this.onClearSelected()
    // },
    modalFormOk(type = '', record = {}) {
      if (type && record && type == 'submit') {
        console.log('哈哈哈哈--');
        
        this.beginProcess(record)
      } else {
        // 新增/修改 成功时，重载列表
        this.loadData();
        // 清空列表选中
        this.onClearSelected()
      }
    },
    handleDetail: function (record) {
      const _path = this.$route.path
      // console.log('path========', _path)

      //debugger;
      if (_path.startsWith('/hmhb/') || _path.startsWith('/scy/') || _path.startsWith('/imp/')
        || _path.startsWith('/erp/')) {
        this.$router.push({
          path: `${_path}Detail/${record.id}`
        })
      } else {
        this.$refs.modalForm.edit(record);
        this.$refs.modalForm.title = '详情';
        this.$refs.modalForm.disableSubmit = true;
      }
      //   console.log(this.$route)
    },
    /* 导出 */
    handleExportXls2() {
      let paramsStr = encodeURI(JSON.stringify(this.getQueryParams()))
      let url = `${window._CONFIG['domianURL']}/${this.url.exportXlsUrl}?paramsStr=${paramsStr}`
      window.location.href = url
    },
    handleExportXls(fileName) {
      this.exportLoading = true
      if (!fileName || typeof fileName !== 'string') {
        fileName = '导出文件'
      }
      let param = this.getQueryParams()
      if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {
        param['selections'] = this.selectedRowKeys.join(',')
      }
      console.log('导出参数', param)
      downFile(this.url.exportXlsUrl, param).then(data => {
        if (!data) {
          this.$message.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(
            new Blob([data], {
              type: 'application/vnd.ms-excel'
            }),
            fileName + '.xls'
          )
        } else {
          let url = window.URL.createObjectURL(
            new Blob([data], {
              type: 'application/vnd.ms-excel'
            })
          )
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) // 下载完成移除元素
          window.URL.revokeObjectURL(url) // 释放掉blob对象
        }
      }).finally(()=>{
        this.exportLoading = false
      })
    },
    /* 导入 */
    handleImportExcel(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (info.file.status === 'done') {
        if (info.file.response.success) {
          // this.$message.success(`${info.file.name} 文件上传成功`);
          if (info.file.response.code === 201) {
            let {
              message,
              result: { msg, fileUrl, fileName }
            } = info.file.response
            let href = window._CONFIG['domianURL'] + fileUrl
            this.$warning({
              title: message,
              content: (
                <div>
                  <span> {msg} </span>
                  <br/>
                  <span>
                    {' '}
                    具体详情请{' '}
                    <a href={href} target="_blank" download={fileName}>
                      {' '}
                      点击下载{' '}
                    </a>{' '}
                  </span>
                </div>
              )
            })
          } else {
            this.$message.success(info.file.response.message || `${info.file.name} 文件上传成功`)
          }
          this.loadData()
        } else {
          this.$message.error(`${info.file.name} ${info.file.response.message}`)
        }
      } else if (info.file.status === 'error') {
        if (info.file.response.status === 500) {
          let data = info.file.response
          const token = Vue.ls.get(ACCESS_TOKEN)
          if (token && data.message.includes('Token失效')) {
            Modal.error({
              title: '登录已过期',
              content: '很抱歉，登录已过期，请重新登录',
              okText: '重新登录',
              mask: false,
              onOk: () => {
                store.dispatch('Logout').then(() => {
                  Vue.ls.remove(ACCESS_TOKEN)
                  window.location.reload()
                })
              }
            })
          }
        } else {
          this.$message.error(`文件上传失败: ${info.file.msg} `)
        }
      }
    },
    /* 图片预览 */
    getImgView(text) {
      if (text && text.indexOf(',') > 0) {
        text = text.substring(0, text.indexOf(','))
      }
      return getFileAccessHttpUrl(text)
    },
    /* 文件下载 */
    // update--autor:lvdandan-----date:20200630------for：修改下载文件方法名uploadFile改为downloadFile------
    downloadFile(text) {
      if (!text) {
        this.$message.warning('无可下载文件')
        return
      }
      if (text.indexOf(',') > 0) {
        text = text.substring(0, text.indexOf(','))
      }
      let url = getFileAccessHttpUrl(text)
      window.open(url)
    },
    //hanyu 在线预览，需要启动kkFileView服务
    viewFile(text) {
      if (!text) {
        this.$message.warning('无可下载文件')
        return
      }
      this.$refs.viewFileModal.show(text);
      // let fileUrl=window._CONFIG['staticDomainURL']+'/'+text
      // let Base64 = require('js-base64').Base64
      // window.open(window._CONFIG['onlinePreviewDomainURL']+'?url='+encodeURIComponent(Base64.encode(fileUrl)));
    },
    initColumns() {
      // 权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
      // this.defColumns = colAuthFilter(this.defColumns,'testdemo:');
      if (this.defColumns) {
        var key = this.$route.name + this.colsettings
        let colSettings = Vue.ls.get(key)
        if (colSettings == null || colSettings == undefined) {
          let allSettingColumns = []
          this.defColumns.forEach(function (item, i, array) {
            allSettingColumns.push(item.dataIndex)
          })
          this.settingColumns = allSettingColumns
          this.columns = this.defColumns
        } else {
          Vue.ls.set(key, colSettings, 7 * 24 * 60 * 60 * 1000)
          this.settingColumns = colSettings
          const cols = this.defColumns.filter(item => {
            if (item.key == 'rowIndex' || item.dataIndex == 'action') {
              return true
            }
            if (colSettings.includes(item.dataIndex)) {
              return true
            }
            return false
          })
          this.columns = cols
        }
      }
    },
    // 列设置更改事件
    onColSettingsChange(checkedValues) {
      var key = this.$route.name + this.colsettings
      Vue.ls.set(key, checkedValues, 7 * 24 * 60 * 60 * 1000)
      this.settingColumns = checkedValues
      const cols = this.defColumns.filter(item => {
        if (item.key == 'rowIndex' || item.dataIndex == 'action') {
          return true
        }
        if (this.settingColumns.includes(item.dataIndex)) {
          return true
        }
        return false
      })
      this.columns = cols
    },
    // table 双击查看详情
    customRow(record) {
      return {
        on: {
          // 事件
          dblclick: event => {
            this.handleDetail(record)
          }
        }
      }
    }
  }
}
